package com.yuanfeng.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.internal.util.AlipaySignature;
import com.yuanfeng.commoms.config.ALiPayConfig;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.MemberMessageListIntegralDTO;
import com.yuanfeng.commoms.dto.oos.OssUploadUpdateParamDTO;
import com.yuanfeng.commoms.dto.order.WapGoodsSaleSumDTO;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.secverifyapiutil.Base64Utils;
import com.yuanfeng.payment.dto.GoodsDTO;
import com.yuanfeng.payment.dto.RecordDTO;
import com.yuanfeng.payment.feign.GoodServiceClient;
import com.yuanfeng.payment.feign.OrderServiceClient;
import com.yuanfeng.payment.feign.ThirdPartyServiceClient;
import com.yuanfeng.payment.feign.UsermsServiceClient;
import com.yuanfeng.payment.mapper.*;
import com.yuanfeng.payment.service.ALiPayService;
import com.yuanfeng.payment.vo.CallBackVO;
import com.yuanfeng.payment.vo.ComsumeRecordVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ALiPayServiceImpl implements ALiPayService {

    final static Logger log = LoggerFactory.getLogger(ALiPayServiceImpl.class);

    @Resource
    private PayConfigMapper payConfigMapper;

    @Resource
    private PayConsumeTradeBackMapper payConsumeTradeBackMapper;

    @Resource
    private PayConsumeTradeMapper payConsumeTradeMapper;

    @Resource
    private PayConsumeRecordMapper payConsumeRecordMapper;

    @Autowired
    private UsermsServiceClient usermsServiceClient;
    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;
    @Autowired
    private OrderServiceClient orderServiceClient;
    @Resource
    private PayUserResourceMapper payUserResourceMapper;
    @Autowired
    private GoodServiceClient goodServiceClient;

    /**
     * 初始化 阿里云支付参数
     */
    public void initAliPayConfig() {
        //从redis中查询
        String payStr = RedisUtil.get(YFConfig.ALI_PAY_CONFIG);
        Map<String, Object> aliPayConfig;
        if (StringUtils.isEmpty(payStr)) {
            aliPayConfig = payConfigMapper.selectPayConfig("03");
        } else {
            aliPayConfig = JSON.parseObject(payStr, Map.class);
            //将支付配置存入Redis
            RedisUtil.set(YFConfig.ALI_PAY_CONFIG, JSON.toJSON(aliPayConfig).toString());
        }
        if (null != aliPayConfig) {
            ALiPayConfig.URL = aliPayConfig.get("gatewayURL").toString();
            ALiPayConfig.APPID = aliPayConfig.get("appID").toString();
            ALiPayConfig.sellerId = aliPayConfig.get("appMCHId").toString();
            ALiPayConfig.RSA_PRIVATE_KEY = aliPayConfig.get("appAPIKey").toString();
            ALiPayConfig.CERT_PATH = aliPayConfig.get("cert_public_key_res2").toString();
            ALiPayConfig.ROOT_CERT_PATH = aliPayConfig.get("cert_root_key").toString();
            ALiPayConfig.ALIPAY_PUBLIC_CERT_PATH = aliPayConfig.get("cert_app_public_key").toString();
            ALiPayConfig.shopping_notify_url = aliPayConfig.get("shoppingNotifyUrl").toString();
            ALiPayConfig.shopping_notify_url_h5 = aliPayConfig.get("rechargeNotifyUrl2").toString();
            ALiPayConfig.shopping_return_url_pc = aliPayConfig.get("shoppingReturnUrlPc").toString();
        }
    }

    @Override
    public void alipayNotifyUrl(HttpServletRequest request, HttpServletResponse response) {
        log.info("----进入异步回调----");
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        try {
            log.info("-----进入开始验签------");
            boolean signVerified = AlipaySignature.rsaCertCheckV1(params, ALiPayConfig.CERT_PATH, ALiPayConfig.CHARSET, ALiPayConfig.SIGNTYPE);
            PrintWriter out = response.getWriter();
            /**
             * 实际验证过程建议商户务必添加以下校验：
             * 1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
             * 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
             * 3、校验通知中的seller_id（或者seller_email)是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
             * 4、验证app_id是否为该商户本身。
             */
            if (signVerified) {
                log.info("-----验签成功----");
                // 商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----out_trade_no-----" + out_trade_no);
                // 支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----trade_no-----" + trade_no);
                // 交易状态
                String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----trade_status-----" + trade_status);
                // 交易订单金额
                String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----total_amount-----" + total_amount);
                // 卖家支付宝用户号
                String seller_id = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----seller_id-----" + seller_id);
                Integer callBackParaListSize = 0;
                String passbackParams = "";
                Object obj = request.getParameter("passback_params");
                if (null != obj) {
                    // 获取存放值
                    passbackParams = URLDecoder.decode(
                            new String(request.getParameter("passback_params").getBytes("ISO-8859-1"), "UTF-8"), "UTF-8");
                    List<CallBackVO> callBackParaList = JsonUtils.string2Obj(passbackParams, List.class,
                            CallBackVO.class);
                    callBackParaListSize = callBackParaList.size();
                }

                // 判断状态
                // 如果状态为TRADE_FINISHED,则交易结束，不可退款
                if (trade_status.equals("TRADE_FINISHED")) {
                    // 判断该笔订单是否在商户网站中已经做过处理
                    // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    // 如果有做过处理，不执行商户的业务程序

                    // 注意：
                    // 如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    // 如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                    out.println("success");
                    out.close();
                } else if (trade_status.equals("WAIT_BUYER_PAY")) {
                    out.println("success");
                    out.close();
                } else if (trade_status.equals("TRADE_CLOSED")) {
                    out.println("success");
                    out.close();
                } else if (trade_status.equals("TRADE_SUCCESS")) {
                    // 更改销量
                    List<WapGoodsSaleSumDTO> wapGood = payUserResourceMapper.queryGoodsByOrderId(out_trade_no);
                    goodServiceClient.updateGoodsSalenum(wapGood);
                    // 订单号是纯数字
                    if (MathUtil.isInteger(out_trade_no)) {
                        //进入回调纯数字订单逻辑处理
                        orderIsInteger(out_trade_no, total_amount, seller_id, trade_no);
                    } else {
                        //进入非纯数字订单逻辑处理
                        orderIsNotInteger(out_trade_no, total_amount, seller_id, trade_no);
                    }
                    out.println("success");
                    out.close();
                }
            } else {
                log.info("验签失败！----- Verify signature error -----------------");
                out.println("fail");
                out.close();
            }
        } catch (Exception e) {
            log.info("alipayNotifyUrlErrorResultsTwo2:" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void alipayPlusNotifyUrl(HttpServletRequest request, HttpServletResponse response) {
        log.info("----进入异步回调----");
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            try {
                params.put(name, valueStr);
            } catch (Exception e) {
                log.info("alipayNotifyUrlErrorResultsOne:" + e.getMessage());
            }
        }

        try {
            log.info("-----进入开始验签------");
            boolean signVerified = AlipaySignature.rsaCertCheckV1(params, ALiPayConfig.CERT_PATH, ALiPayConfig.CHARSET, ALiPayConfig.SIGNTYPE);
            log.info("----------------" + signVerified + "==" + ALiPayConfig.CERT_PATH);
            PrintWriter out = response.getWriter();
            /**
             * 实际验证过程建议商户务必添加以下校验： 1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
             * 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）， 3、校验通知中的seller_id（或者seller_email)
             * 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
             * 4、验证app_id是否为该商户本身。
             */
            if (signVerified) {
                log.info("-----验签成功----");
                // 商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----out_trade_no-----" + out_trade_no);
                // 支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----trade_no-----" + trade_no);
                // 交易状态
                String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----trade_status-----" + trade_status);
                // 交易订单金额
                String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----total_amount-----" + total_amount);
                // 卖家支付宝用户号
                String seller_id = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"), "UTF-8");
                log.info("-----seller_id-----" + seller_id);

                Integer callBackParaListSize = 0;
                String passbackParams = "";
                Object obj = request.getParameter("passback_params");
                Map map = new HashMap();
                if(null != obj) {
                    // 获取存放值
                    passbackParams = URLDecoder.decode(
                            new String(request.getParameter("passback_params").getBytes("ISO-8859-1"), "UTF-8"), "UTF-8");
                    System.out.println("-----passbackParams-----" + passbackParams);
                    map = JsonUtils.string2Obj(passbackParams, Map.class);
                    System.out.println("-----plus的map-----" + map.get("token"));
                    map.put("plusOrder",map.get("out_trade_no"));
                }

                if (trade_status.equals("TRADE_FINISHED")) {
                    // 判断该笔订单是否在商户网站中已经做过处理
                    // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    // 如果有做过处理，不执行商户的业务程序

                    // 注意：
                    // 如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    // 如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                    out.println("success");
                    out.close();
                } else if (trade_status.equals("WAIT_BUYER_PAY")) {
                    out.println("success");
                    out.close();
                } else if (trade_status.equals("TRADE_CLOSED")) {
                    out.println("success");
                    out.close();
                } else if (trade_status.equals("TRADE_SUCCESS")) {
                    log.info("----TRADE_SUCCESS---");
                    // 更改销量
                    List<WapGoodsSaleSumDTO> wapGood = payUserResourceMapper.queryGoodsByOrderId(out_trade_no);
                    goodServiceClient.updateGoodsSalenum(wapGood);
                    //插入plus会员信息
                    map.put("type",4);
                    ResponseResult plusmemberopen = usermsServiceClient.plusmemberopen(map);
                    if (plusmemberopen.getCode() == 1 || plusmemberopen.getCode() == 3){
                        // 结果已处理，返回success
                        out.println("success");
                        out.close();
                    }else{
                        out.println("fail");
                        out.close();
                    }
                }
            } else {
                log.info("验签失败！----- Verify signature error -----------------");
                out.println("fail");
                out.close();
            }
        } catch (Exception e) {
            log.info("alipayNotifyUrlErrorResultsTwo2:" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 当支付单号为纯数字订单
     *
     * @param outTradeNo
     * @param totalAmount
     * @param sellerId
     * @param tradeNo
     */
    public void orderIsInteger(String outTradeNo, String totalAmount, String sellerId, String tradeNo) {
        Map<String, String> orderIdIsNum = new HashMap<>();
        //虚拟订单 0是 1否
        Integer virtualGoods = null;
        //门店订单 1 是 2否
        Integer orderIsShopTake = null;
        RecordDTO queryGoodsPara = payConsumeTradeBackMapper.queryRecordPriceAndName(outTradeNo);
        //判断订单是否已支付成功
        if (!queryGoodsPara.getOrderStateId().equals(6)) {
            String orderId = queryGoodsPara.getOrderId();
            String recordMoney = queryGoodsPara.getTradePaymentAmount();
            if (outTradeNo.equals(orderId) && totalAmount.equals(recordMoney)
                    && sellerId.equals(ALiPayConfig.sellerId)) {
                payConsumeTradeMapper.updateConsumeTradePaymentMoney(outTradeNo, 3);
                orderIdIsNum.put("orderId", outTradeNo);
                //订单号是数字
                orderIdIsNum.put("isNum", "0");

                //判断是否是积分商品订单 并修改用户积分
                updateUserJIfen(outTradeNo);
                //判断是否是虚拟订单
                Map<String, Integer> judgeOrderMap = this.virtualWxExchangeCode(orderIdIsNum);
                virtualGoods = judgeOrderMap.get("virtualGoods");
                orderIsShopTake = judgeOrderMap.get("orderIsShopTake");
                Map<Object, Object> map = new HashMap<Object, Object>();
                // 支付方式
                Integer payCode = CommonType.payType.PAY_TYPE_ZFB.getCode();
                // 待发货
                Integer orderStatus = CommonType.orderStatus.TO_BE_SHIPPED.getCode();
                //虚拟订单 0 是 1 否
                if (null != virtualGoods && virtualGoods.equals(CommonType.orderType.IS_VIRTUAL.getCode())) {
                    //如果是虚拟订单就将订单状态修改为 已发货
                    orderStatus = CommonType.orderStatus.SHIPPED.getCode();
                }
                //门店订单 1 是 2 否
                if (null != orderIsShopTake && orderIsShopTake.equals(CommonType.orderType.IS_SHOP_TAKE.getCode())) {
                    //如果是门店订单就将订单状态修改为 已发货
                    orderStatus = CommonType.orderStatus.SHIPPED.getCode();
                }
                // 支付方式
                Integer paymentId = CommonType.payType.ONLINE_PAY.getCode();
                // 支付方式名称
                String paymentName = "在线支付";
                // 支付时间
                String paymentTime = DateUtils.getNowDateToString();
                // 第三方支付号
                String paymentOtherNumber = tradeNo;
                // 支付方式
                map.put("payCode", payCode);
                map.put("paymentId", paymentId);
                // 商户订单号
                map.put("paymentNumber", outTradeNo);
                map.put("orderStatus", orderStatus);
                map.put("paymentName", paymentName);
                map.put("paymentTime", paymentTime);
                map.put("paymentOtherNumber", paymentOtherNumber);
                orderServiceClient.HFiveUpdateOrderBaseByPayment(map);
                // 更改支付表状态ConsumeRecord
                Integer recordStatus = 3;
                Map<String, Object> mapPureDigital = new HashMap<>();
                mapPureDigital.put("recordStatus", recordStatus);
                mapPureDigital.put("paymentTime", paymentTime);
                mapPureDigital.put("outTradeNo", outTradeNo);
                payConsumeRecordMapper.updateComsumeRecordByPureDigital(mapPureDigital);
                // 发送feign,提交下单通知
                Map<String, Object> messageMap = new HashMap<String, Object>();
                // 支付号
                messageMap.put("orderId", outTradeNo);
                messageMap.put("paymentTime", paymentTime);
                // 发送下单通知
                orderServiceClient.orderToInform(messageMap);
                // 更改ConsumeTrade
                Integer orderStateId = 3;
                String closeTime = DateUtils.getNowDateToString();

                Map<String, Object> mapDigital = new HashMap<>();
                mapDigital.put("orderStateId", orderStateId);
                mapDigital.put("paymentTime", paymentTime);
                mapDigital.put("closeTime", closeTime);
                mapDigital.put("outTradeNo", outTradeNo);
                payConsumeTradeBackMapper.updateConsumeTradeByPureDigital(mapDigital);

            } else {
                log.info("订单号或订单金额不符！");
            }
        }
    }

    /**
     * 当支付单号不是纯数字订单
     *
     * @param outTradeNo
     * @param totalAmount
     * @param sellerId
     * @param tradeNo
     */
    public void orderIsNotInteger(String outTradeNo, String totalAmount, String sellerId, String tradeNo) {
        Map<String, String> orderIdIsNum = new HashMap<>();
        //虚拟订单 0是 1否
        Integer virtualGoods = null;
        //门店订单 1 是 2否
        Integer orderIsShopTake = null;
        // 订单号不是纯数字Record表查询
        List<Integer> recodeStatus = payConsumeRecordMapper.queryRecodeStatus(outTradeNo);
        orderIdIsNum.put("orderId", outTradeNo);
        //订单号不是是数字
        orderIdIsNum.put("isNum", "1");
        //判断是否是积分商品订单 并修改用户积分
        updateUserJIfen(outTradeNo);
        //判断是否是虚拟订单
        Map<String, Integer> judgeOrderMap = this.virtualWxExchangeCode(orderIdIsNum);
        virtualGoods = judgeOrderMap.get("virtualGoods");
        orderIsShopTake = judgeOrderMap.get("orderIsShopTake");
        // 判断订单状态是否改变
        for (int i = 0; i < recodeStatus.size(); i++) {
            String orderId = null;
            if (recodeStatus.get(i) == 1) {
                List<ComsumeRecordVO> payConsumeRecord = payConsumeRecordMapper.queryorderNo(outTradeNo);
                BigDecimal money = new BigDecimal(0);
                for (int j = 0; j < payConsumeRecord.size(); j++) {
                    money = money.add(payConsumeRecord.get(j).getRecordMoney());
                }
                orderId = payConsumeRecord.get(0).getOrderId();
                String recordMoney = money.toString();
                if (outTradeNo.equals(orderId) && totalAmount.equals(recordMoney)
                        && sellerId.equals(ALiPayConfig.sellerId)) {
                    Map<Object, Object> map = new HashMap<Object, Object>();
                    // 支付方式
                    Integer payCode = 2;
                    // 待发货
                    Integer orderStatus = 3;
                    //虚拟订单 0 是 1 否
                    if (null != virtualGoods && 0 == virtualGoods) {
                        //如果是虚拟订单就将订单状态修改为 已发货
                        orderStatus = 4;
                    }
                    //门店订单 0 是 1 否
                    if (null != orderIsShopTake && 0 == orderIsShopTake) {
                        //如果是门店订单就将订单状态修改为 已发货
                        orderStatus = 4;
                    }
                    // 支付方式
                    Integer paymentId = 1;
                    // 支付方式名称
                    String paymentName = "在线支付";
                    // 支付时间
                    String paymentTime = DateUtils.getNowDateToString();
                    // 第三方支付号
                    String paymentOtherNumber = tradeNo;
                    // 支付方式
                    map.put("payCode", payCode);
                    map.put("paymentId", paymentId);
                    // 商户订单号
                    map.put("paymentNumber", outTradeNo);
                    map.put("orderStatus", orderStatus);
                    map.put("paymentName", paymentName);
                    map.put("paymentTime", paymentTime);
                    map.put("paymentOtherNumber", paymentOtherNumber);
                    orderServiceClient.HFiveUpdateOrderBaseByPayment(map);
                    // 更改支付表状态ConsumeRecord
                    Integer recordStatus = 3;
                    Map<String, Object> mapPureDigital = new HashMap<>();
                    mapPureDigital.put("recordStatus", recordStatus);
                    mapPureDigital.put("paymentTime", paymentTime);
                    mapPureDigital.put("outTradeNo", outTradeNo);
                    payConsumeRecordMapper.updateComsumeRecord(mapPureDigital);
                    // 更改ConsumeTrade
                    Integer orderStateId = 3;
                    String closeTime = DateUtils.getNowDateToString();
                    Map<String, Object> mapDigital = new HashMap<>();
                    mapDigital.put("orderStateId", orderStateId);
                    mapDigital.put("paymentTime", paymentTime);
                    mapDigital.put("closeTime", closeTime);
                    mapDigital.put("outTradeNo", outTradeNo);
                    payConsumeTradeBackMapper.updateConsumeTrade(mapDigital);


                    // 发送feign,提交下单通知
                    Map<String, Object> messageMap = new HashMap<String, Object>();
                    // 支付号
                    messageMap.put("orderId", outTradeNo);
                    messageMap.put("paymentTime", paymentTime);
                    // 发送下单通知
                    orderServiceClient.orderToInform(messageMap);
                } else {
                    log.info("订单号或订单金额不符");
                }
            }
        }
    }

    /**
     * 如果是积分订单就 修改用户积分
     *
     * @param orderId
     */
    public void updateUserJIfen(String orderId) {
        Integer amountAotalIntegral = null;
        //积分商品 0  是  1 否
        Integer integralGoods = 1;
        //是纯数字
        RecordDTO queryGoodsPara = null;
        if (MathUtil.isInteger(orderId)) {
            queryGoodsPara = payConsumeTradeBackMapper.queryRecordPriceAndNameByTradeId(orderId);
        } else {//不是纯数字
            queryGoodsPara = payConsumeTradeBackMapper.queryRecordPriceAndName(orderId);
        }
        if (null == queryGoodsPara) {
            return;
        }
        GoodsDTO queryGoodsPara2 = payConsumeTradeBackMapper.queryGoodsPriceAndName(queryGoodsPara.getOrderId(), queryGoodsPara.getBuyerId());
        if (null == queryGoodsPara2 && null != queryGoodsPara2.getTotalIntegral()) {
            return;
        }
        //获取积分商品订单的积分
        Integer totalIntegral = queryGoodsPara2.getTotalIntegral();
        //积分商品 0  是  1 否
        integralGoods = queryGoodsPara2.getIntegralGoods();
        amountAotalIntegral = totalIntegral;
        if (null != integralGoods && integralGoods == 0) {
            //获取用户积分
            Integer userIntegral = usermsServiceClient.getMemberIntegralByUserId(queryGoodsPara.getBuyerId());
            if (null != userIntegral && amountAotalIntegral <= userIntegral) {
                //扣除积分
                //修改会员积分和会员等级
                MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                ArrayList<String> list = new ArrayList<>();
                list.add(queryGoodsPara.getBuyerId());
                updateMemberMessageListIntegral.setUserIdList(list);
                updateMemberMessageListIntegral.setIntegral(amountAotalIntegral);
                //1是增加积分 0 是扣除积分
                updateMemberMessageListIntegral.setType(CommonType.commonStatus.NO.getCode());
                usermsServiceClient.updateMemberIntegral(updateMemberMessageListIntegral);
                //添加积分修改记录
                Map<String, Object> pointParam = new HashMap<>();
                pointParam.put("PointsLogType", CommonType.pointsLogType.CONSUME.getCode());
                pointParam.put("ClassId", CommonType.pointType.POINTS_EXCHANGE_GOODS.getCode());
                pointParam.put("PointsLogTime", new Date());
                pointParam.put("PointsLogDesc", CommonType.pointType.POINTS_EXCHANGE_GOODS.getDesc());
                pointParam.put("PointsLogFlag", "reg");
                pointParam.put("UserId", queryGoodsPara.getBuyerId());
                pointParam.put("PointsLogPoints", amountAotalIntegral);
                pointParam.put("PointsLogOperate", CommonType.pointType.POINTS_EXCHANGE_GOODS.getDesc());
                usermsServiceClient.insertPointLogByMap(pointParam);
            }
        }
    }

    /**
     * 微信小程序支付回调判断该订单是否是 虚拟 / 自提 订单 如果是 生成兑换码
     *
     * @param orderIdIsNum
     */
    public Map<String, Integer> virtualWxExchangeCode(Map<String, String> orderIdIsNum) {
        Integer virtualGoods = null;
        String orderId = null;
        String redeemCodeUrl = null;
        String code = null;
        Integer orderIsShopTake = null;
        Map<String, Integer> judgeOrderMap = new HashMap<>();
        try {
            ResponseResult res = orderServiceClient.isVirtualOrder(orderIdIsNum);
            if(null!=res.getData()){
                Map<String, Object> map = (Map<String, Object>) res.getData();
                virtualGoods =Integer.valueOf(map.get("virtualGoods").toString());
                orderId = (String) map.get("orderId");
                orderIsShopTake = Integer.valueOf(map.get("orderIsShopTake").toString());
            }

            //虚拟订单 0 是 1 否
            if (null != virtualGoods && 0 == virtualGoods || null != orderIsShopTake && 1 == orderIsShopTake) {
                SimpleDateFormat df = new SimpleDateFormat("ddHHmmss");
                String timeStamp = df.format(new Date());
                String temp = String.valueOf(Math.round((Math.random() + 1) * 1000));
                code = temp + timeStamp;
                //生成二维码 上传oss
                byte[] b = QrCodeUtil.createQRCode(150, 150, code);
                //上传oss
                String encode = Base64Utils.encode2(b);
                OssUploadUpdateParamDTO param = new OssUploadUpdateParamDTO();
                param.setBase64Str(encode);
                param.setStreamName(".png");
                ResponseResult responseResult = thirdPartyServiceClient.uploadToOssBase64(param);
                //生成核销二维码
                redeemCodeUrl = (String) responseResult.getData();
                Map<String, Object> param2 = new HashMap<>();
                param2.put("order", orderId);
                param2.put("redeemCode", code);
                param2.put("redeemCodeUrl", redeemCodeUrl);
                //为虚拟拟订单添加兑换码
                payConsumeTradeBackMapper.addRedeemCode(param2);
            }

            judgeOrderMap.put("virtualGoods", virtualGoods);
            judgeOrderMap.put("orderIsShopTake", orderIsShopTake);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return judgeOrderMap;
    }
}
